import showImgPreview from '../components/imgPreview/index';
import showAudioPreview from '../components/audioPreview/index';
import showVideoPreview from '../components/videoPreview/index';
import showPopFilePreview from '../components/popFilePreview/index';
import request from '@/utils/request'
import
{
    getDwgToPdfUrl,
    getOpenDownloadFile,
    getOpenDownloadUrl,
    getOpenOfdDownloadUrl,
    getWordPreviewUrl,
} from '../api/common/attachment';
import { getDownloadUrl } from 'hc-core-vue3/api/common/filedata'
import { formatDate, buildPDFPreviewUrl } from '../utils/index';
import store from "@/store";
import { ElMessage, ElMessageBox } from 'element-plus';
import { openWpsOnlineLink } from "../event/eventClick";
//加载wps
if (window.HC_config.VUE_APP_isInstallWps)
{
    installWps();
}
// 统一封装 文件预览函数
const base_url = localStorage.getItem("local_server_ip") || window.HC_config.VITE_APP_BASE_API || process.env.VITE_APP_BASE_API;


/**
 * 通过文件名获取文件类型
 * @param { String } P_FileName 文件名
 * @returns { String }
 */
export function getFileTypeByFileName(P_FileName)
{
    let fileType = "";
    const matches = /\.([^.]+)$/.exec(P_FileName);
    if (matches)
    {
        fileType = matches ? matches[1] : '';
    }
    return fileType.toLowerCase();
}

//文件预览函数
function filePreview(file, isDown = false, P_FormType, p_ModuleName)
{
    //通过文件名获取文件类型
    const fileType = getFileTypeByFileName(file.fileName);
    console.log(file, 'file');
    const fileMime = window.HC_config.VUE_APP_LIST_PREVIEW_MIME || [];
    if ("wps" == fileType || "et" == fileType)
    {
        if (window.HC_config.VUE_APP_isInstallWps)
        {
            if ("et" == fileType)
            {
                //xls预览方式
                try
                {
                    viewExcelWithAttachment(
                        base_url,
                        file.unid,
                        ""
                    );
                } catch (err)
                {
                    ElMessage.info("该文件不支持在线预览!")
                }
            }
            else
            {
                try
                {
                    viewDocumentWithAttachment(
                        base_url,
                        file.unid,
                        ""
                    );
                } catch (err)
                {
                    ElMessage.info("该文件不支持在线预览!")
                }
            }
        }
        else
        {
             //只读打开在线链接
             openWpsOnlineLink(file.unid, "attachment", "read", 0);
        }
    }
    else if ((fileMime.includes(fileType)
        && (window.HC_config.VUE_APP_POP_FILE_PREVIEW || window.HC_config.VUE_APP_WINDOW_FILE_PREVIEW)))
    {
        if (window.HC_config.VUE_APP_POP_FILE_PREVIEW)
        {
            // 修改配置 VUE_APP_POP_FILE_PREVIEW 弹窗预览文件
            showPopFilePreview(file);
        }
        else
        {
            p_ModuleName = p_ModuleName || file.moduleName;
            // 修改配置 VUE_APP_WINDOW_FILE_PREVIEW 打开新窗口预览文件
            window.open(`/listpreview?type=${file.type}&unid=${file.unid}&relationUnid=${file.relationUnid}&formType=${P_FormType}&moduleName=${p_ModuleName}&isDown=${isDown}&print=${!isDown}`);
        }
    }
    else if (['pdf', 'dwg', 'caj'].includes(fileType)
        && window.HC_config.VUE_APP_SHOW_PDF_PREVIEW)
    {
        //pdf打开方式
        pdfFilePreview(file, isDown);
    }
    else if (isImgFile(file.fileName))
    {
        if (window.HC_config.VUE_APP_WINDOW_IMG)
        {
            // 打开新窗口预览文件
            window.open(`/listpreview?type=${file.type}&unid=${file.unid}&relationUnid=${file.relationUnid}`);
        }
        else
        {
            //图片预览方式
            showImgPreview(getOpenDownloadFile(file.filePath))
        }
    } else if (isAudioFile(file.fileName))
    {
        //音频
        showAudioPreview(getOpenDownloadFile(file.filePath))
    }
    else if (isVideoFile(file.fileName))
    {
        //视屏
        showVideoPreview(getOpenDownloadFile(file.filePath))
    }
    else if (file.fileName.indexOf(".ofd") != -1)
    {
        //ofd预览方式
        ofdFilePreview(file);
    }
    else if (file.fileName.indexOf(".xls") != -1)
    {
        //xls预览方式
        try
        {
            viewExcelWithAttachment(
                base_url,
                file.unid,
                ""
            );
        } catch (err)
        {
            ElMessage.info("该文件不支持在线预览!")
        }
    }
    else if (file.fileName.indexOf(".txt") != -1)
    {
        //对于gd文件 下载
        let requestParams = {
            url: getOpenDownloadUrl(file.unid),
            method: "get",
            responseType: 'blob'
        };
        //执行请求
        request(requestParams)
            .then((res) =>
            {
                if (res instanceof Blob)
                {
                    //创建Blob对象
                    let blob = new Blob([res], { type: "text/plain;charset=utf-8" });
                    let tempFile = new File([blob], 'test.text', { type: blob.type });
                    let reader = new FileReader(); // 读取TXT起重要作用的
                    reader.readAsText(tempFile);
                    reader.onload = oFREvent =>
                    { // 读取完毕从中取值
                        let pointsTxt = oFREvent.target.result;
                        console.log('pointsTxt', pointsTxt) // 获取到的TXT文件
                        ElMessageBox.alert("<pre>" + pointsTxt + "</pre>", file.fileName, {
                            showConfirmButton: false,
                            dangerouslyUseHTMLString: true,
                            customClass: "text-previe-box"
                        })
                    };
                }
                else if (res.data instanceof Blob)
                {
                    //创建Blob对象
                    let blob = new Blob([res.data], { type: "text/plain;charset=utf-8" });
                    let tempFile = new File([blob], 'test.text', { type: blob.type });
                    let reader = new FileReader(); // 读取TXT起重要作用的
                    reader.readAsText(tempFile);
                    reader.onload = oFREvent =>
                    { // 读取完毕从中取值
                        let pointsTxt = oFREvent.target.result;
                        console.log('pointsTxt', pointsTxt) // 获取到的TXT文件
                        ElMessageBox.alert("<pre>" + pointsTxt + "</pre>", file.fileName, {
                            showConfirmButton: false,
                            dangerouslyUseHTMLString: true,
                            customClass: "text-previe-box"
                        })
                    };
                }
            })
    }
    else if (file.fileName.indexOf(".gd") != -1)
    {
        //对于gd文件 下载
        let requestParams = {
            url: getOpenDownloadUrl(file.unid),
            method: "get",
            responseType: 'blob'
        };

        let fileName = file.fileName;
        //执行请求
        request(requestParams)
            .then((res) =>
            {
                if (res instanceof Blob)
                {
                    download(res, fileName);
                }
                else if (res.data instanceof Blob)
                {
                    download(res.data, fileName);
                }
            })

    }

    else if (['et', 'xlsx', 'xls'].includes(fileType))
    {
        try
        {
            viewExcelWithAttachment(
                base_url,
                file.unid,
                ""
            )
        }
        catch (err)
        {
            ElMessage.info("该文件不支持在线预览!")
        }
    }
    else
    {
        console.log("本地地址", base_url);
        if (file.fileType == 'url')
        {
            // 打开新页面
            var urlStr = file.filePath + '&isPreview=' + true
            window.open(urlStr, "_blank");
        }
        else
        {
            try
            {
                viewDocumentWithAttachment(
                    base_url,
                    file.unid,
                    ""
                );
            } catch (err)
            {
                ElMessage.info("该文件不支持在线预览!")
            }
        }
    }
}

// 判断是否为图片类型文件
function isImgFile(fileName)
{
    var suffix = `(bmp|jpg|png|tif|gif|pcx|tga|exif|fpx|svg|psd|cdr|pcd|dxf|ufo|eps|ai|raw|WMF|webp|jpeg|BMP|JPG|PNG|TIF|GIF|PCX|TGA|EXIF|FPX|SVG|PSD|CDR|PCD|DXF|UFO|EPS|AI|RAW|WMF|WEBP|JPEG)`;
    var regular = new RegExp(`.*\.${suffix}`);
    return regular.test(fileName);
}


// 判断是否为视屏
function isVideoFile(fileName)
{
    var suffix = `(swf|flv|mp4|rmvb|avi|mpeg|ra|ram|mov|wmv)`;
    var regular = new RegExp(`.*\.${suffix}`);
    return regular.test(fileName);
}


//判断是否为音频
function isAudioFile(fileName)
{
    var suffix = `(mp3|wav|wma|ogg|ape|acc)`;
    var regular = new RegExp(`.*\.${suffix}`);
    return regular.test(fileName);
}


//pdf文件预览
function pdfFilePreview(file, isDown = false)
{
    const fileType = getFileTypeByFileName(file.fileName);

    //判断是否启用另一种pdf预览功能
    if (window.HC_config.VUE_APP_SHOW_PDF)
    {
        let url = `${base_url}/attachment/api/downloadUnid/?unid=${file.unid}#download=0`;
        if (['docx', 'doc', 'caj'].includes(fileType))
        {
            url = getWordPreviewUrl(file.unid);
        } else if (['dwg'].includes(fileType))
        {
            url = getDwgToPdfUrl(file.unid);
        }
        let urlParams = {
            file: url,
            download: isDown,
            filename: file.fileName || "文件.pdf",
        };
        let herf = buildPDFPreviewUrl(urlParams);
        window.open(herf);
    } else
    {
        // 判断是否用福昕打开pdf
        if (window.HC_config.VUE_APP_OPEN_PDF)
        {
            // 判断电脑系统，window系统用在线打开pdf  否则用福昕打开
            var agent = localStorage.getItem('agentOS')
            if (agent && agent == 'window')
            {
                window.open("/showpdf?type=attachment&unid=" + file.unid + "&showWatermask=" + window.HC_config.VUE_APP_PDF_WATERMARK);
            }
            else
            {
                let filePath = getOpenOfdDownloadUrl(file.unid);
                let markText = store.getters.userInfo.personCommonname + '\n ' + formatDate(new Date(), '{y}-{m}-{d}');
                filePath = window.btoa(filePath);
                var addWaterMarkTxt = encodeURI(
                    `${markText},10,10,30,20,仿宋_GB2312,14,FF0000,all,1,20,20;${markText},10,100,30,20,仿宋_GB2312,14,FF9900,all,1,20,20`
                );
                addWaterMarkTxt = decodeURI(addWaterMarkTxt);
                let link = document.createElement("a");
                link.href = `kpofd://openUrl=${filePath}&fCompUnVisible=open,save,saveas,print,snapshot,hand,uploadfile,clipprint,selecttext&AddWaterMarkTxt=${addWaterMarkTxt}`;
                link.click();
            }
        }
        else
        {
            window.open("/showpdf?type=attachment&unid=" + file.unid + "&fileName=" + file.fileName + "&showWatermask=" + window.HC_config.VUE_APP_PDF_WATERMARK);
        }
    }
}

//ofd文件预览
function ofdFilePreview(file)
{
    console.log("---ofd--")
    console.log(typeof process.env.VUE_APP_OPEN_OFD);
    //判断是否启用福昕打开ofd
    if (window.HC_config.VUE_APP_OPEN_OFD)
    {
        // 判断电脑系统，window系统用在线打开pdf  否则用福昕打开
        var agent = localStorage.getItem('agentOS')
        if (agent && agent == 'window')
        {
            window.open(`/zxfw/ofdview.html?file=${file.unid}`)
        }
        else
        {
            let filePath = getOpenOfdDownloadUrl(file.unid);
            let userName = store.getters.userInfo.personCommonname + '\n ' + formatDate(new Date(), '{y}-{m}-{d}');
            filePath = window.btoa(filePath);
            let addWaterMarkTxt = encodeURI(
                `${userName},10,10,30,20,仿宋_GB2312,14,FF0000,all,1,20,20;${userName},10,100,30,20,仿宋_GB2312,14,FF9900,all,1,20,20`
            );
            addWaterMarkTxt = decodeURI(addWaterMarkTxt);
            let link = document.createElement("a");
            link.href = `kpofd://openUrl=${filePath}&fCompUnVisible=open,save,saveas,print,snapshot,hand,uploadfile,clipprint,selecttext&AddWaterMarkTxt=${addWaterMarkTxt}`;
            link.click();
        }
    } else
    {
        // window.open(`/zxfw/showofd.html?unid=${file.unid}`);
        window.open(`/zxfw/ofdview.html?file=${file.unid}`)
    }
}

//加载wps
function installWps()
{
    var element = document.createElement("script");
    element.src = "/officeplugin2/js/CustomDocFunctionV2.js";
    document.body.appendChild(element);
    var element2 = document.createElement("script");
    element2.src = "/officeplugin2/js/wps.js";
    document.body.appendChild(element2);
    var element_et = document.createElement("script");
    element_et.src = "/officeplugin2/js/et.js";
    document.body.appendChild(element_et);
    var element3 = document.createElement("script");
    element3.src = "/officeplugin2/js/wps_sdk.js";
    document.body.appendChild(element3);
}

//下载文件
function download(data, fileName)
{
    if (!data)
    {
        return;
    }
    let url = window.URL.createObjectURL(new Blob([data]));
    let link = document.createElement("a");
    link.style.display = "none";
    link.href = url;
    link.setAttribute("download", fileName);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

/**
 * 格式文件链接
 * @param {Object} P_Item 文件
 * @param {String} P_ModuleName 模块名称
 * @returns 
 */
export function formatFileUrl(P_Item, P_ModuleName, P_ZwType) 
{
    if (
        P_Item.fileType == "docx"
        || P_Item.fileType == "doc"
        || P_Item.fileType == "caj"
    )
    {
        if (P_ZwType == 'contract' && P_ModuleName == 'fwgl')
        {
            let base_url = localStorage.getItem("local_server_ip") || window.HC_config.VITE_APP_BASE_API || process.env.VITE_APP_BASE_API;
            let url = base_url + "/sign/contract/showFile/?unid=" + P_Item.parentUnid + "#download=0"
            return url
        }
        else
        {
            return getWordPreviewUrl(P_Item.unid);
        }
    } else if (P_Item.fileType == "dwg")
    {
        return getDwgToPdfUrl(P_Item.unid);
    }
    if (P_ModuleName == 'fwgl' && P_Item.parentUnid)
    {
        return getDownloadUrl(P_Item.parentUnid)
    }
    return getOpenDownloadUrl(P_Item.unid);
}



/**
 * 文件圈阅
 * @param { Object } options
 * @param { String } options.file 文件链接
 * @param { String } options.moduleName 模型名称
 * @param { String } options.fileName 文件名称
 * @param { String } options.formType 表单类型
 * @param { String } options.fileUnid 文件unid
 * @param { String } options.unid 表单unid
 */
export function fileQyPreview(options)
{
    var file = options.file
    var moduleName = options.moduleName
    var unid = options.unid
    var fileName = options.fileName
    var formType = options.formType
    var fileUnid = options.fileUnid
    window.open('/redlining?moduleName=' + moduleName + '&unid=' + unid + '&fileUnid=' + fileUnid + '&fileName=' + encodeURIComponent(fileName) + '&formType=' + formType + '&url=' + file)
}

export default filePreview